<template>
    <div class="role">
        <el-table v-loading="tableLoading" :data="roleData" style="width: 100%; margin-bottom: 20px" row-key="roleid" border
            default-expand-all>
            <el-table-column header-align="center" prop="roleid" label="角色id" />

            <el-table-column align="center" prop="roleName" label="角色名称">
                <template #default="{ row }">
                    <el-tag size:="large" class="mx-1" effect="dark" round>
                        {{ row.roleName }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="desc" label="角色描述">
                <template #default="{ row }">
                    <el-tag size:="large" type="success" class="mx-1" effect="dark" round>
                        {{ row.desc }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="status" label="角色状态">
                <template #default="{ row }">
                    <el-switch v-model="row.status" @change="switchChange(row)"
                        :disabled="!isChild(userStore.userInfo.value.roleid, row.roleid, roleStore.allRoles)" active-value="1"
                        inactive-value="0" size="large" inline-prompt active-text="启用"
                        style="--el-switch-on-color: #1c8bda; --el-switch-off-color: #ff4949"
                        inactive-text="禁用"></el-switch>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="address" label="操作">
                <template #default="{ row }">
                    <el-button type="primary" @click="handleGranRole(row)" v-access="row.roleid">分配权限</el-button>
                    <el-button type="warning" v-access="row.roleid">分配角色</el-button>
                </template>
            </el-table-column>
        </el-table>
        <sDrawer v-model="drawerShow" :opened="getPermissionRoleList" @ok="save">
            <!-- 树形结构 -->
            <template #nested>
                <el-tree ref="treeRef" highlight-current check-on-click-node check-strictly :data="treedData" show-checkbox
                    node-key="id" default-expand-all :props="treeProps" />
            </template>
        </sDrawer>
    </div>
</template>
<script setup>
import { ref, onMounted } from "vue"
// 引入获取角色列表的接口
import * as api from "@/api/permission"
// 引入抽屉组件
import sDrawer from "@/components/sDrawer/index.vue"
// 引入弹出框
import { ElMessage, ElMessageBox } from "element-plus"
// 引入当前角色id的store
import usePermission from "@/store/permission"
// 引入userStore
import useUser from "@/store/users"
// 引入角色的store
import useRole from "@/store/role"
// 引入封装的判断节点是否是父级节点的方法
import isChild from "@/utils/isChild"
// 引入修改角色的接口
import { updateRoleApi } from "@/api/role"
// 使用角色的store
let roleStore = useRole()
// 使用userStore
let userStore = useUser()
// console.log(userStore.userInfo.value.roleid);
// 使用当前角色id的store
let { currentPermissionsIds } = usePermission()
// 控制抽屉显示与隐藏
let drawerShow = ref(false)
let roleData = ref([])
// 控制表格的加载动画
let tableLoading = ref(false)
// 引用树形组件
let treeRef = ref(null)

// 点击的当前角色的id
let currentRoleid = ref(null)

// 获取角色列表
let getRoleList = async () => {
    tableLoading.value = true
    try {
        let res = await api.getRoleListApi()
        roleData.value = res.data.data
        tableLoading.value = false
    } catch (e) {
        console.log(e);
        tableLoading.value = false
    }
}

// 树形控件的数据
const treeProps = {
    children: 'children',
    label: 'desc',
}


// 点击分配触发的逻辑
let handleGranRole = (row) => {
    // console.log(row);
    drawerShow.value = true
    currentRoleid.value = row.roleid
}
// 树形结构的数据
const treedData = ref([])
// 请求角色树形数据和所有的权限数据
let getPermissionRoleList = async () => {
    try {
        //并发请求所有权限数据和角色权限数据
        let res = await Promise.all([api.getPermissionListApi(), api.getRolePermissionListApi({ type: '1', roleid: currentRoleid.value })])
        //   console.log(res);
        // 所有的权限数据
        let allPermissionData = res[0].data.permissionPaths
        // 当前角色的权限数据
        let currentRolePermissionData = res[1].data.data
        // console.log(treeRef.value);
        // 设置树形的选中状态
        // 处理选中id
        let checked_ids = currentRolePermissionData.map(item => item.id)
        treeRef.value.setCheckedKeys(checked_ids)

        // 将所有的权限数据扁平化处理
        let flatTreeData = (data = []) => {
            // 声明一个接收扁平化数据的数组
            let flatArr = []
            // 声明递归的函数
            let recursion = (arr = []) => {
                arr.forEach(item => {
                    // 声明一个对象存放存储扁平化处理后的数据
                    let obj = {
                        "_id": item._id,
                        "id": item.id,
                        "desc": item.desc,
                        "path": item.path,
                        "method": item.method,
                        "parentid": item.parentid,
                        "permission": item.permission,
                    }
                    // 判断item是否有children
                    if (item.children && item.children.length > 0) {
                        recursion(item.children)
                    }
                    flatArr.push(obj)
                })
            }
            recursion(data)
            return flatArr
        }
        // 扁平数据的结果
        let flatAllPermission = flatTreeData(allPermissionData)
        // 和角色拥有的权限数据进行对比,如果没有对应的数据,就添加一个disabled属性
        // 判断是不是超级管理员
        if (userStore.userInfo.value.roleid !== '1') {
            flatAllPermission.forEach(item => {
                if (!currentPermissionsIds.includes(item.id)) {
                    item.disabled = true
                }
            })
        }

        // 将flatAllPermission转换成树形结构
        let toTreeData = (data = []) => {
            // 声明一个接收树形结构的数组
            let tree = []
            // 遍历data
            data.forEach(item => {
                // 判断是否有parentid
                if (!item.parentid) {
                    tree.push(item)
                } else {
                    // 有parentid 通过parentid找到对应的父级
                    let parent = data.find(v => v.id === item.parentid)
                    // 判断父级是否有children
                    if (!parent.children) {
                        parent.children = []
                    }
                    parent.children.push(item)
                }
            })
            return tree
        }

        let treeAllPermission = toTreeData(flatAllPermission)
        // console.log(treeAllPermission);
        // 给树形赋值
        treedData.value = treeAllPermission
    } catch (e) {
        console.log(e);
    }
}
// 抽屉组件点击确定触发的事件
let save = () => {
    // console.log('点击了保存');
    // 获取选中的id
    let permission_ids = treeRef.value.getCheckedKeys()
    // console.log(permission_ids);
    // 弹出确认框
    ElMessageBox.confirm('确认分配权限吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 确认分配权限
        try {
            let res = await api.grantRoleApi({ roleids: [currentRoleid.value], permission_ids })
            console.log(res);
            if (res.data.code === 200) {
                // 关闭抽屉
                drawerShow.value = false
                // 提示
                ElMessage.success('权限分配成功')
                // 重新获取角色列表
                getRoleList()
            }
        } catch (e) {
            console.log(e);
        }
    }).catch(() => {
        ElMessage.info('已取消权限分派')
    })
}
// 声明自定义指令控制按钮的禁用状态
let vAccess = {
    mounted(el, binding) {
        // console.log(el);
        // console.log(binding);
        // 获取当前角色id
        let currentRoleid = userStore.userInfo.value.roleid
        // 获取目标的角色id
        let targetRoleid = binding.value
        // 获取角色列表
        let roleList = roleStore.allRoles
        // 调用判断节点是否是父级节点的方法
        let isChildRole = isChild(currentRoleid, targetRoleid, roleList)
        // 保存当前按钮的类名
        let className = el.className
        if (!isChildRole) {
            // 父级节点 禁用按钮
            el.className = className + ' is-disabled'
            el.disabled = true
        }
    }
}
// 声明点击角色状态切换状态
let switchChange = async (row) => {
    console.log(row.parentid);
    //发起修改请求
    try {
        await updateRoleApi({ status: row.status, roleid: row.roleid })
        // 提示
        if (row.status === '1') {
            ElMessage.success(row.roleName + '角色启用成功')
        } else {
            ElMessage.error(row.roleName + '角色禁用成功')
        }
    } catch (e) {
        console.log(e);
    }
}

onMounted(() => {
    getRoleList()
})
</script>z``